package com.city.ajax.grid;

import com.city.config.Code;
import com.city.domain.city.CityCopnotePerson;
import com.city.domain.pub.PubUser;
import com.city.domain.report.*;
import com.city.format.CtCountFormat;
import com.city.helper.FormatHelper;
import com.city.service.city.CityCopnotePersonService;
import com.city.service.pub.PubUserService;
import com.city.service.report.*;
import com.city.helper.EntityHelper;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @deprecation: 移动网格ajax
 * @email: leichuqiao@126.com
 * @author: 雷楚桥
 * @date: 2018/7/23 14:53
 */
@RestController
@RequestMapping("/ajax/grid")
public class  GridAjax {

    @Autowired
    private ReportService reportService;
    @Autowired
    private EntityHelper entityHelper;
    @Autowired
    private FileService fileService;
    @Autowired
    private CityCopnotePersonService cpService;
    @Autowired
    private PubUserService userService;
    @Autowired
    private CtLegalPersonService legalPersonService;
    @Autowired
    private CtGeospatialService geospatialService;
    @Autowired
    private CtCroplandService croplandService;
    @Autowired
    private CtBuildService buildService;
    @Autowired
    private CtPartService partService;
    @Autowired
    private CtPartCategorySmallService smallService;
    @Autowired
    private CtPartCategoryBigService bigService;
    @Autowired
    private CtBranchService ctBranchService;
    @Autowired
    private CtCountService ctCountService;

    /**
     * @deprecation 查询村庄
     * @param townId Integer 乡镇id
     * @return cityVillageList
     * @author 雷楚桥
     * @date 2018/7/23 14:54
     */
    @ResponseBody
    @RequestMapping("/getVillage")
    public Map<String,Object> getVillage(@Param("townId") Integer townId){
        Map<String,Object> map = new HashMap<>();
        if(townId != null)
            map.put("data",reportService.findCityVillageByTownId(townId));

        map.put("code",townId != null ? Code.SUCCESS: Code.ERROR);
        return map;
    }

    /**
     * @deprecation 查询乡镇
     * @return Map
     * @author 雷楚桥
     * @date 2018/7/25 14:28
     */
    @ResponseBody
    @RequestMapping("/getTown")
    public Map<String,Object> getTown() {
        Map<String,Object> map = new HashMap<>();
        map.put("data",reportService.findAllCityTown());
        map.put("code", Code.SUCCESS);
        return map;
    }

    /**
     * @deprecation 查询事件分类
     * @param categoryId Integer 上报类别
     * @param parent Integer 需要查询的上级目录
     * @return Map
     * @author 雷楚桥
     * @date 2018/7/25 14:31
     */
    @ResponseBody
    @RequestMapping("/getEvent")
    public Map<String,Object> getCtEvent(@Param("categoryId") Integer categoryId,
                                         @Param("parent") Integer parent){
        Map<String,Object> map = new HashMap<>();
        map.put("data",reportService.findAllCtEventByCategoryIdAndParent(categoryId,parent));
        map.put("code", Code.SUCCESS);
        return map;
    }

    /**
     * @deprecation 保存上报案件
     * @param categoryId Integer 上报分类
     * @param typeBig Integer 案件分类[大类]
     * @param typeSmall Integer 案件分类[小类]
     * @param title String 案件标题[简介]
     * @param content String 案件内容
     * @param townId Integer 乡镇id
     * @param villageId Integer 村庄id
     * @return Map
     * @author 雷楚桥
     * @date 2018/7/23 16:52
     */
    @ResponseBody
    @RequestMapping("/saveReport")
    public Map<String,Object> saveReport(   @Param("categoryId") Integer categoryId,
                                            @Param("typeBig") Integer typeBig,
                                            @Param("typeSmall") Integer typeSmall,
                                            @Param("title") String title,
                                            @Param("content") String content,
                                            @Param("townId") Integer townId,
                                            @Param("villageId") Integer villageId){
        Map<String,Object> map = new HashMap<>();
        CtReport ctReport = entityHelper.createReport(categoryId,typeBig,typeSmall,title,content,townId,villageId);
        ctReport.setIsDoBan(0);
        map.put("data",reportService.saveCtReport(ctReport));
        map.put("code", Code.SUCCESS);
        return map;
    }

    /**
     * @deprecation 保存上报案件saveReport
     * @param param String 参数
     * @return Map
     * @author 雷楚桥
     * @date 2018/7/23 16:52
     */
    @ResponseBody
    @RequestMapping("/saveReportEvent")
    public Map<String,Object> saveReportEvent(@Param("param") String param,
                                              @Param("taskId") String taskId){
        Map<String,Object> map = new HashMap<>();
        JSONObject json = new JSONObject(param);

        CtReport report = entityHelper.createReport(json);
        report.setTaskId(taskId);
        System.out.println(taskId);
        report.setIsDoBan(0);
        report.setIsontime(0);
        report.setIsrework(0);
        CtReport rep = reportService.saveCtReport(report);

        Integer pId = rep.getId();

        JSONObject files = json.getJSONObject("files");
        Iterator<String> it = files.keys();
        while(it.hasNext()){
            String src = (String)files.get(it.next());
            CtFile file = entityHelper.createFile("ct_report",pId,src);
            fileService.saveFile(file);
        }
        map.put("code", Code.SUCCESS);
        return map;
    }
    
    
    /**
     * @deprecation 保存民情日记
     * @param param String 参数
     * @return Map
     * @author 雷楚桥
     * @date 2018-08-24 10:41
     */
    @ResponseBody
    @RequestMapping("/saveCopnote")
    public Map<String,Object> saveCopnote(@Param("param") String param,@Param("taskId") String taskId){
        Map<String,Object> map = new HashMap<>();
        JSONObject json = new JSONObject(param);

        //保存民情日记
        CtCopnote copnote = entityHelper.createCopnote(json);
        System.out.println(taskId);
        copnote.setTaskId(taskId);
        CtCopnote cop = reportService.saveCopnote(copnote);

        Integer cId = cop.getId();

        //保存文件
        JSONObject files = json.getJSONObject("files");
        Iterator<String> it = files.keys();
        while(it.hasNext()){
            String src = (String)files.get(it.next());
            CtFile file = entityHelper.createFile("ct_copnote",cId,src);
            fileService.saveFile(file);
        }

        //保存民情日记被仿人员记录
        JSONArray personList = json.getJSONArray("personList");
        for(int i = 0,len = personList.length(); i< len ; i++){
            CityCopnotePerson person = entityHelper.createCopnotePerson(personList.getJSONObject(i));
            person.setCopnoteId(cId);
            cpService.save(person);
        }

        map.put("code", Code.SUCCESS);
        map.put("data",copnote);
        return map;
    }
    
    /**
     * @deprecation 保存扶贫信息
     * @param param String 请求参数
     * @return 
     * @author 雷楚桥
     * @date 2018-08-24 16:29
     */
    @ResponseBody
    @RequestMapping("/savePoor")
    public Map<String,Object> savePoor(@Param("param") String param){
        Map<String,Object> map = new HashMap<>();
        JSONObject json = new JSONObject(param);
        PubUser user = entityHelper.createUser(json);
        user.setAuthLevel(0);
        user.setNohRegister("农村户口");
        user.setPoliticalOutlook("5");
        user = userService.saveUser(user);
        map.put("code", Code.SUCCESS);
        map.put("data",user);
        return map;
    }

    /**
     * @Author: 李顺时
     * @param param String 请求参数
     * @Description: 保存法定代表人信息
     * @Date: 16:51 2018/9/7
     */
    @ResponseBody
    @RequestMapping("/savelegalperson")
    public Map<String,Object> saveLegalPerson(@Param("param") String param){
        Map<String,Object> map = new HashMap<>();
        System.out.println(param);
        JSONObject json = new JSONObject(param);
        CtLegalPerson legalPerson = entityHelper.createLegalPerson(json);
        legalPerson = legalPersonService.saveLegalPerson(legalPerson);
        map.put("code", Code.SUCCESS);
        map.put("data",legalPerson);
//        map.put("data",0);
        return map;
    }

    /**
     * @Author: 李顺时
     * @param param String 请求参数
     * @Description: 保存地理空间信息
     * @Date: 16:51 2018/9/7
     */
    @ResponseBody
    @RequestMapping("/savegeospatial")
    public Map<String,Object> saveGeospatial(@Param("param") String param){
        Map<String,Object> map = new HashMap<>();
        JSONObject json = new JSONObject(param);
        CtGeospatial geospatial = entityHelper.createGeospatial(json);
        geospatial = geospatialService.saveGeospatial(geospatial);
        map.put("code", Code.SUCCESS);
        map.put("data",geospatial);
        return map;
    }

    /**
     * @Author: 李顺时
     * @param param String 请求参数
     * @Description: 保存农地信息
     * @Date: 16:52 2018/9/7
     */
    @ResponseBody
    @RequestMapping("/savecropland")
    public Map<String,Object> saveCropland(@Param("param") String param){
        Map<String,Object> map = new HashMap<>();
        JSONObject json = new JSONObject(param);
        CtCropland ctCropland = entityHelper.createCropland(json);
        ctCropland = croplandService.saveCropland(ctCropland);
        map.put("code", Code.SUCCESS);
        map.put("data",ctCropland);
        return map;
    }

    /**
     * @Author: 李顺时
     * @param param String 请求参数
     * @Description: 保存建筑物信息
     * @Date: 16:52 2018/9/7
     */
    @ResponseBody
    @RequestMapping("/savebuild")
    public Map<String,Object> saveBuild(@Param("param") String param){
        Map<String,Object> map = new HashMap<>();
//        System.out.println(param);
        JSONObject json = new JSONObject(param);
        CtBuild ctBuild = entityHelper.createBuild(json);
        ctBuild = buildService.saveBuild(ctBuild);
        map.put("code", Code.SUCCESS);
        map.put("data",ctBuild);
//        map.put("data",1);

        return map;
    }

    /**
     * @Author: 李顺时
     * @param param String 请求参数
     * @Description: 保存部件信息
     * @Date: 16:52 2018/9/7
     */
    @ResponseBody
    @RequestMapping("/savepart")
    public Map<String,Object> savePart(@Param("param") String param){
        Map<String,Object> map = new HashMap<>();
        JSONObject json = new JSONObject(param);
        CtPart ctPart = entityHelper.createPart(json);
        ctPart = partService.savePart(ctPart);
        map.put("code", Code.SUCCESS);
        map.put("data",ctPart);
        return map;
    }


    /**
     * @Author: 李顺时
     * @Description: 查询一级分类
     * @Date: 15:53 2018/9/9
     */
    @ResponseBody
    @RequestMapping("/getBigType")
    public Map<String,Object> getBigType() {
        Map<String,Object> map = new HashMap<>();
        map.put("data",bigService.findALl());
        map.put("code", Code.SUCCESS);
        return map;
    }

    /**
     * @Author: 李顺时
     * @Description: 查询二级分类
     * @param bigCode
     * @Date: 15:52 2018/9/9
     */
    @ResponseBody
    @RequestMapping("/getSmallType")
    public Map<String,Object> getSmallType(@Param("bigCode") String bigCode){
        Map<String,Object> map = new HashMap<>();
        if(bigCode != null)
            map.put("data",smallService.findGategoryByBigcode(bigCode));

        map.put("code",bigCode != null ? Code.SUCCESS: Code.ERROR);
        return map;
    }


    /**
     * @Author: 李顺时
     * @Description: 修改数据。。。测试用
     * @Date: 14:55 2018/9/12
     */
//    @ResponseBody
//    @RequestMapping("/savebranchNotIn")
//    public Map<String,Object> savebranchNotIn(){
//        Map<String,Object> map = new HashMap<>();
//        List<String> name =new ArrayList<>();
//        String[] arr = {"县规划建设和城镇管理监察执法大队",
//                "兴文县交管大队",
//                "古宋镇政府",
//                "县平台中心",
//                "僰王山镇政府",
//                "共乐镇政府",
//                "兴文县住建和城管局环卫所",
//                "大坝苗族乡政府",
//                "大河苗族乡政府",
//                "五星镇政府",
//                "莲花镇政府",
//                "太平镇政府",
//                "玉屏镇政府",
//                "兴文县电信公司",
//                "兴文县住建和城管局建管股",
//                "兴文县住建和城管局园林所",
//                "兴文县电信公司B",
//                "麒麟苗族乡政府",
//                "九丝城镇政府",
//                "石海镇政府",
//                "仙峰苗族乡政府",
//                "周家镇政府",
//                "毓秀苗族乡政府",
//                "兴文县工业园区",
//                "兴文县石海旅游公司",
//                "兴文县僰王山旅游公司",
//                "兴文县移动公司",
//                "兴文县交通局",
//                "兴文县住建和城管局房地产管理股 ",
//                "兴文县广电网络公司",
//                "项目公司",
//                "兴文县电力公司",
//                "兴文县水务局",
//                "县教体文广局",
//                "兴文县运管局",
//                "宜宾市公路局兴文养护段",
//                "兴文县工商局",
//                "兴文县城投公司",
//                "兴文县公安消防大队",
//                "兴文县联通公司",
//                "兴文县经商科技局",
//                "宜宾市路政直属三大队",
//                "兴文县民政局",
//                "兴文县畜牧局",
//                "兴文县自来水公司"};
//        for(String n : arr){
//            name.add(n);
//        }
//
//        List<CtBranch> ctBranches =  ctBranchService.findAll();
//        List<CtCount> ctCounts = ctCountService.findAll();
//
//        System.out.println(ctBranches);
//        Integer i = 0;
//        for(String branchname : name) {
//
//            CtBranch branch = new CtBranch();
//            boolean flag = false;
//            for (CtBranch cb : ctBranches) {
//                if(branchname.equalsIgnoreCase(cb.getName())){
//                    flag = true;
//                    System.out.println(branchname+"存在,id为:"+cb.getId());
//
//                    ctCounts.get(i).setBranchId(cb.getId());
//                    ctCountService.save(ctCounts.get(i));
//                    break;
//                };
//            }
//            i++;
//
//
////            if(!flag){
////                branch.setName(branchname);
////                branch.setParent(0);
////                branch.setType(0);
////                System.out.println(branchname+"不存在，重新添加");
////                ctBranchService.save(branch);
////            }
//        }
//        return map;
//    }


    @PostMapping("/department_count")
    @ResponseBody
    public Map<String,Object> seachUser(
            @Param(value = "limitPage" ) Integer limitPage,
            @Param(value ="limitNum") Integer limitNum ){
        Map<String,Object> map = new HashMap<String,Object>();
        FormatHelper formatHelper = new FormatHelper();
        List<CtCountFormat> ctCountFormats = new ArrayList<>();
        List<CtBranch> ctBranches = ctBranchService.findAll();
        List<CtCount> ctCounts = ctCountService.findByPageAndLimit(limitPage,limitNum);
        for(CtCount c :ctCounts){
            String branchName = "部门未录入";
            for(CtBranch cb: ctBranches){
                if(cb.getId() == c.getBranchId()){
                    branchName = cb.getName();
                    break;
                }
            }
            CtCountFormat ctCountFormat = formatHelper.ctCountFormat(c, branchName);
            ctCountFormats.add(ctCountFormat);
        }
        map.put("data",ctCountFormats );
        map.put("res", "1");
        map.put("code", "成功");
        map.put("count",ctCountService.count());
        return map;
    }



}
